package com.zk.shop.service.Impl;

import com.zk.shop.dao.CartDao;
import com.zk.shop.entity.CartItem;
import com.zk.shop.entity.User;
import com.zk.shop.service.CartService;
import com.zk.shop.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {

    private SqlSession sqlSession = null;
    private CartDao cartDao = null;
    @Override
    public int addCart(CartItem cartItem) {
        int result = 0;
        try{
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            cartDao = sqlSession.getMapper(CartDao.class);
            result = cartDao.addCart(cartItem);
            sqlSession.commit();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    @Override
    public int updateBuyNum(CartItem cartItem) {
        int result = 0;
        try{
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            cartDao = sqlSession.getMapper(CartDao.class);
            result = cartDao.updateBuyNum(cartItem);
            sqlSession.commit();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    @Override
    public int delCartItem(CartItem cartItem) {
        int result = 0;
        try{
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            cartDao = sqlSession.getMapper(CartDao.class);
            result = cartDao.delCartItem(cartItem);
            sqlSession.commit();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    @Override
    public int selGoods(CartItem cartItem) {
        int result = 0;
        try{
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            cartDao = sqlSession.getMapper(CartDao.class);
            result = cartDao.selGoods(cartItem);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return result;
    }

    @Override
    public List<CartItem> showCart(User user) {
        List<CartItem> cartItemList = new ArrayList<>();
        try{
            sqlSession = SqlSessionFactoryUtil.getSqlSession();
            cartDao = sqlSession.getMapper(CartDao.class);
            cartItemList = cartDao.showCart(user);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            sqlSession.close();
        }
        return cartItemList;
    }
}
